package com.zhika.zishi.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.view.WindowManager;

/**
 * Created by Michael on 2015/4/3.
 * 处理图片
 */
public class PictureUtil {

    private static final String TAG = "PictureUtil";

    /**
     * 按比例缩放图片
     * @param context 对应的上下文context
     * @param id 资源中的图片
     * @param scale 比例大小
     * @return 返回缩小后的图片
     */
    public static Bitmap zoomScalePicture(Context context,int id,int scale) {

        Bitmap bitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();

        try {
            options.inJustDecodeBounds = true;

            BitmapFactory.decodeResource(context.getResources(), id, options);

            DisplayMetrics metrics = getScreenWG(context);

            int oldBitmapWidth = options.outWidth;
            LogUtil.e(TAG,"oldBitmapWidth = "+oldBitmapWidth);

            int newBitmapWidth = metrics.widthPixels/scale;
            LogUtil.e(TAG,"newBitmapWidth = "+newBitmapWidth);
            int be = 1;

            if (oldBitmapWidth > newBitmapWidth){
                be = oldBitmapWidth/newBitmapWidth;
            }

            options.inSampleSize = be;

            LogUtil.e(TAG,""+options.inSampleSize);
            options.inJustDecodeBounds = false;

            options.inPreferredConfig= Bitmap.Config.RGB_565;

            bitmap = BitmapFactory.decodeResource(context.getResources(),id,options);

            LogUtil.e(TAG,"图片最终的宽度 = "+bitmap.getWidth());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 得到存放屏幕宽高的DisplayMetrics
     * @param context
     * @return
     */
    public static DisplayMetrics getScreenWG(Context context){
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        DisplayMetrics metrics = new DisplayMetrics();

        manager.getDefaultDisplay().getMetrics(metrics);

        return metrics;
    }
}
